
from hashlib import md5
import execjs,requests
from urllib.parse import urlencode
from copyheaders import headers_raw_to_dict

# 合成请求参数
def mergeParam( e ):

    # js 函数生成加密签名
    js = open(r'./bv.js', mode='r', encoding='utf-8').read()

    cxt = execjs.compile(js)

    params = cxt.call('params',e )

    # md5生成加密bv
    ua = b'5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'

    m = md5()

    m.update(ua)

    bv = m.hexdigest()
    # 加密参数
    data = {

        'i': e,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': params['salt'],
        'sign': params['sign'],
        'ts': params['ts'],
        'bv': bv,
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTlME',
    }

    return data

# 翻译函数
def translateJson(e):
    # 定义请求头
    headers = headers_raw_to_dict(

        b'''
        Accept: application/json, text/javascript, */*; q=0.01
        Accept-Encoding: gzip, deflate
        Accept-Language: zh-CN,zh;q=0.9
        Connection: keep-alive
        Content-Length: 251
        Content-Type: application/x-www-form-urlencoded; charset=UTF-8
        Cookie: OUTFOX_SEARCH_USER_ID_NCOO=1604442332.4693456; OUTFOX_SEARCH_USER_ID="187294463@10.168.11.12"; _ga=GA1.2.264379895.1564110460; _gid=GA1.2.12702883.1571304685; JSESSIONID=aaa1MV8_R6QS6cYInNC3w; SESSION_FROM_COOKIE=unknown; ___rl__test__cookies=1571371498797
        Host: fanyi.youdao.com
        Origin: http://fanyi.youdao.com
        Referer: http://fanyi.youdao.com/
        User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36
        '''
    )

    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

    data = urlencode( mergeParam( e ) )

    r = requests.post( url=url,headers=headers,data=data)

    result = r.json()['translateResult'][0][0]['tgt']

    print( '英语翻译结果:%s'%result )

if __name__ == '__main__':

    content = input('请输入想要翻译内容:')

    translateJson( content )











